package cn.uin.domain.oss.service;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MinioService
 * @Description:Minio操作服务类
 * @Author: Administrator
 * @CreateDate: 2025/11/4 15:45
 * @Version: 1.0
 */
@Component
public class MinioService {

	@Autowired
	private MinioClient minioClient;

	/**
	 * 检查存储桶是否存在
	 * @param bucketName
	 * @return
	 * @throws Exception
	 */
	public boolean bucketExists(String bucketName) throws Exception {
		return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
	}

	/**
	 * 创建存储桶
	 * @param bucketName
	 * @throws Exception
	 */
	public void createBucket(String bucketName) throws Exception {
		if (!bucketExists(bucketName)) {
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
		}
	}

	/**
	 * 上传文件
	 * @param bucketName
	 * @param objectName
	 * @param file
	 * @throws Exception
	 */
	public void uploadFile(String bucketName, String objectName, MultipartFile file) throws Exception {
		// 确保默认桶存在
		createBucket(bucketName);
		InputStream is = file.getInputStream();
		minioClient.putObject(PutObjectArgs.builder()
						.bucket(bucketName)
						.object(objectName)
						.stream(is, file.getSize(), -1)
						.contentType(file.getContentType())
						.build());
		is.close();
	}

	/**
	 * 下载文件
	 * @param bucketName
	 * @param objectName
	 * @return
	 * @throws Exception
	 */
	public InputStream downloadFile(String bucketName, String objectName) throws Exception {
		return minioClient.getObject(GetObjectArgs.builder()
						.bucket(bucketName)
						.object(objectName)
						.build());
	}

	/**
	 * 删除文件
	 * @param bucketName
	 * @param objectName
	 * @throws Exception
	 */
	public void deleteFile(String bucketName, String objectName) throws Exception {
		minioClient.removeObject(RemoveObjectArgs.builder()
						.bucket(bucketName)
						.object(objectName)
						.build());
	}

	/**
	 * 获取文件访问URL（临时链接，有效期1小时）
	 * @param bucketName
	 * @param objectName
	 * @return
	 * @throws Exception
	 */
	public String getFileUrl(String bucketName, String objectName) throws Exception {
		return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
						.bucket(bucketName)
						.object(objectName)
						.method(Method.GET)
						.expiry(1, TimeUnit.HOURS)
						.build());
	}

	/**
	 * 获取所有存储桶列表
	 * @return
	 * @throws Exception
	 */
	public List<Bucket> getAllBuckets() throws Exception {
		return minioClient.listBuckets();
	}

}
